package net.wapproject.utils;

import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.ImageIcon;
import org.apache.log4j.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiWriter;
import com.sun.jimi.core.options.JPGOptions;

public class ImageSave {
	private static final Logger logger = Logger.getLogger(Image.class);

	/**
	 * method resize image.
	 * @param imagedata
	 * @param newWidth
	 * @param newHeight
	 * @return image resized
	 */
	public static byte[] resizeImage(byte[] imagedata, int newWidth, int newHeight) {
		Image image = new ImageIcon(imagedata).getImage();
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			Image img = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
			JimiWriter jimiWriter = Jimi.createJimiWriter("image/jpeg", out);
			JPGOptions options = new JPGOptions();
			options.setQuality(100);
			jimiWriter.setOptions(options);
			jimiWriter.setSource(img);
			jimiWriter.putImage(out);
			out.flush();
			return out.toByteArray();
		} catch (Throwable t) {
			t.printStackTrace();
			return imagedata;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception ignore) {}
			}
		}
	}
	
	/**
	 * method save and resize image from my computer.
	 * @param file
	 * @param filePath
	 * @param newW
	 * @param newH
	 */
	public static void saveAndResize(File file, String filePath, int newW, int newH) {
		final String location = "save() - ";
		logger.debug(location + "BEGIN");
		try {
			byte[] data = FileUtils.readFileToByteArray(file);
			byte[] resizedData = resizeImage(data, newW, newH);
			String diskUrl = ConfigurationUtils.get(ConfigurationUtils.KEY_SOURCE_FOLDER);
        	String path = diskUrl + filePath;
			FileUtils.writeByteArrayToFile(new File(path), resizedData);
		} catch (Exception e) {
			logger.error(location, e);
		}
		logger.debug(location + "END");
	}
	
	/**
	 * method save image from my computer.
	 * @param file
	 * @param filePath
	 */
	public static void save(File file, String filePath) {
		final String location = "save() - ";
		logger.debug(location + "BEGIN");
		try {
			byte[] data = FileUtils.readFileToByteArray(file);
			String diskUrl = ConfigurationUtils.get(ConfigurationUtils.KEY_SOURCE_FOLDER);
        	String path = diskUrl + filePath;
        	System.out.println("sssssss" + path);
			FileUtils.writeByteArrayToFile(new File(path), data);
		} catch (Exception e) {
			logger.error(location, e);
		}
		logger.debug(location + "END");
	}
	
	/**
	 * method save image from link
	 * @param fileLink
	 * @param filePath
	 */
	public static void save(String fileLink, String filePath) {
		final String location = "save() - ";
		logger.debug(location + "BEGIN");
		try {
			fileLink = fileLink.replace(" ", "%20");
            URL url = new URL(fileLink);
			InputStream in = url.openStream();
			byte[] data = IOUtils.toByteArray(in);
			String diskUrl = ConfigurationUtils.get(ConfigurationUtils.KEY_SOURCE_FOLDER);
        	String pathFull = diskUrl + filePath;
			FileUtils.writeByteArrayToFile(new File(pathFull), data);
		} catch (Exception e) {
			logger.error(location, e);
		}
		logger.debug(location + "END");
	}
	
	public static String getImgFromContent(String content) {
		String img = "";
		try {
			int a = content.indexOf("src=");
			int b = content.indexOf(".jpg");
			b = content.indexOf(".jpg");
			if ( b == -1) {
				b = content.indexOf(".gif");
				if ( b == -1) {
					b = content.indexOf(".jpeg") + 1;
				}
			}
			img = content.substring(a+5, b+4);
		} catch (Exception e) {
			img = Constants.NOT_AVATAR;
		}
		return img;
	}
	

	public static void main(String[] args) {
		System.out.println(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		//save("http://i854.photobucket.com/albums/ab105/xemanh/hoang-hon-tren-cau02.jpg","/1/test2.jpg");
	}
	
}
